/**
 * 1. promise 是一个类，在创建的时候传入一个函数，会立即调用，这个函数称为执行器
 * 2. 执行器有两个参数，resolve,reject
 * 3. promise 中有三种状态，resolve 和 reject 可以改变这些状态
 *      这些状态分别是：pending(等待)、fulfilled（成功）、rejected（失败）
 *      初始状态为pending，一旦这个状态发生了改变，就不会被更改了
 * 4. then 方法传入两个回调函数，分别得到成功的值和失败的原因，内部是通过状态来判断调用的是哪个回调
 */
// 这里定义三个常亮，供内部来使用
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
    // 构造函数，传入一个执行器
    constructor (executor) {
        // 执行器会传入两个方法供外部调用
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }

    // 内部的状态 初始为pending
    status = PENDING
    // 成功的值
    value = undefined
    // 失败的原因
    reason = undefined
    // 失败回调
    successCallBack = []
    // 成功回调
    failCallBack = []
    /**
     * 1. 用来把状态改为fulfilled
     * 2. 接收回调任务成功的值
     */
    resolve = value => {
        // 因为状态只能被改变一次，所以这里要加上判断
        if (this.status !== PENDING) return
        // 将状态改为成功
        this.status = FULFILLED
        // 保存成功的值
        this.value = value
        // 执行成功后的回调
        // this.successCallBack && this.successCallBack(this.value)
        while (this.successCallBack.length) this.successCallBack.shift()()
    }

    /**
     * 1. 用来把状态改为rejected
     * 2. 接收回调任务失败的原因
     */
    reject = reason => {
        // 因为状态只能被改变一次，所以这里要加上判断
        if (this.status !== PENDING) return
        this.status = REJECTED
        this.reason = reason
        // this.failCallBack && this.failCallBack(this.reason)
        while (this.failCallBack.length) this.failCallBack.shift()()
    }

    /**
     * 
     */

    then(successCallBack, failCallBack) {
        successCallBack = successCallBack ? successCallBack : value => value
        failCallBack = failCallBack ? failCallBack : reason => { throw reason }
        let promise2 = new MyPromise((resolve, reject) => {
            // 判断状态
            if (this.status === FULFILLED) {
                setTimeout(() => {
                    try {
                        // 执行成功的回调，并传入成功的值
                        let res = successCallBack(this.value)
                        // resolve(res)
                        resolvePromise(promise2, res, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                    
                },0)
            } else if (this.status === REJECTED) {
                // 执行失败的回调，并传入失败的原因
                setTimeout(() => {
                    try {
                        // 执行成功的回调，并传入成功的值
                        let res = failCallBack(this.reason)
                        // resolve(res)
                        resolvePromise(promise2, res, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                    
                },0)
                
            } else {
                // 这里状态是等待，任务是异步的
                // this.successCallBack = successCallBack
                // this.failCallBack = failCallBack
                this.successCallBack.push(() => {
                    setTimeout(() => {
                        try {
                            // 执行成功的回调，并传入成功的值
                            let res = successCallBack(this.value)
                            // resolve(res)
                            resolvePromise(promise2, res, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                        
                    },0)
                })
                this.failCallBack.push(() => {
                     // 执行失败的回调，并传入失败的原因
                    setTimeout(() => {
                        try {
                            // 执行成功的回调，并传入成功的值
                            let res = failCallBack(this.reason)
                            // resolve(res)
                            resolvePromise(promise2, res, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                        
                    },0)
                })
            }
        })
        
        return promise2
    }

    finally (callback) {
        // callback()
        return this.then(value => {
            MyPromise.resolve(callback()).then(() => value)
        }, reason => {
            MyPromise.resolve(callback()).then(() => { throw reason })
        })
    }

    catch (failCallBack) {
        return this.then(undefined, failCallBack)
    }

    static all (arr) {
        let res = []
        let index = 0
        return new MyPromise((resolve, reject) => {
            function addData(i, v) {
                res[i] = v
                index++
                console.log(index, res.length)
                if (arr.length === index) {
                    resolve(res)
                }
            }
            for (let i = 0; i < arr.length; i++) {
                let cur = arr[i]
                if (cur instanceof MyPromise) {
                    cur.then(value => addData(i, value), reason => reject(reason))
                } else {
                    addData(i, cur)
                }
            }
        })
    }

    static resolve(value) {
        if (value instanceof MyPromise) return value
        return new MyPromise(resolve => resolve(value))
    }
}

function resolvePromise(promise2, res, resolve, reject) {
    if (promise2 === res) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (res instanceof MyPromise) {
        res.then(resolve, reject)
    } else {
        resolve(res)
    }
}

function makeMyPromise(v, t) {
    return new MyPromise((reslove, reject) => {
        setTimeout(() => {
            reslove(v)
        }, t)
    }) 
}

MyPromise.all(['1', '2', '3', makeMyPromise('a', 1000), makeMyPromise('b', 2000), '2']).then(res => console.log(res))
